﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using Newtonsoft.Json;

namespace ConsoleSocket
{
    public class Program
    {
        private static IPAddress ip;
        public static void Main(string[] args)
        {
            IPHostEntry iPs = Dns.GetHostEntry(Dns.GetHostName());
            foreach (IPAddress i in iPs.AddressList)
            {
                if (i.AddressFamily == AddressFamily.InterNetwork)
                {
                    ip = i;
                    break;
                }
            }
            SocketService();
            Console.ReadKey();
        }
        public static void SocketService()
        {
            int port = 8090;
            IPEndPoint ipe = new IPEndPoint(ip, port);
            Socket sSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            sSocket.Bind(ipe);
            Console.WriteLine("服务器地址：{0}:{1}", ip, port);
            Console.WriteLine("监听已经打开，请等待");
            sSocket.Listen(0);
            while (true)
            {
                Thread test = new Thread(new ThreadStart(() => {
                    Start(sSocket);
                }));
                test.Start();
            }
        }
        public static void Start(Socket socket)
        {
            Socket serverSocket = socket.Accept();
            string UserId = ((IPEndPoint)serverSocket.RemoteEndPoint).Port.ToString();
            Console.WriteLine("连接已经建立");
            Console.WriteLine($"用户ID：{UserId}");
            //Console.WriteLine($"Connected Staus:{serverSocket.Poll(1000, SelectMode.SelectRead)}");
            while (true)
            {
                if (serverSocket.Poll(1000, SelectMode.SelectRead))
                {
                    serverSocket.Close();
                    Console.WriteLine("连接已断开");
                    break;
                }
                else
                {
                    Sends(serverSocket, "123");
                }
            }
        }
        public static void Sends(Socket socket, string msg)
        {
            byte[] getMsg = new byte[4096];
            socket.Receive(getMsg, 0, getMsg.Length, SocketFlags.None);
            Console.WriteLine("getMsg:{0}\r\n", Encoding.UTF8.GetString(getMsg));

            byte[] sendMsg = Encoding.UTF8.GetBytes(msg);
            socket.Send(getMsg, 0, getMsg.Length, SocketFlags.None);
            Console.WriteLine("sendMsg:{0}\r\n", msg);
            Console.WriteLine(DateTime.Now + "\r\n");
        }
    }
}
/*
            //取出RequestHeader中Sec-WebSocket-Accept值
            //var StringMsg = Encoding.UTF8.GetString(getMsg);
            //var str = Regex.Match(StringMsg, "Sec-WebSocket-Key: (.*)").Value;
            //if (!string.IsNullOrEmpty(str))
            //{
            //    str = str.Split(":")[1];
            //}
            //str = str.Trim();

            //计算返回的Sec-WebSocket-Accept值
            //byte[] sha = SHA1.Create().ComputeHash(Encoding.ASCII.GetBytes(str + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"));
            //var secKey = Convert.ToBase64String(sha);

            //ResponseHeader
            //var header = string.Empty;
            //header += "HTTP/1.1 101 Switching Protocols\r\n";
            //header += "Upgrade:websocket\r\n";
            //header += "Connection:Upgrade\r\n";
            //header += $"Sec-WebSocket-Accept:{secKey}";
         */